from microdot import Microdot
import time,jpeg,camera,network

def connect():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print('esp32p4正在联网',end="")
        wlan.connect('ssid', 'PWD') 
        while not wlan.isconnected():
            print(".",end="")
            time.sleep(1)
    print('\n网络信息为: ', wlan.ifconfig())
    ifconfig = wlan.ifconfig()
    print('请在浏览器打开:{}:5000'.format(ifconfig[0]))

connect()
app = Microdot()
camera.init()

@app.route('/')
def index(request):
    return '''<!doctype html>
<html>
  <head>
    <title>ESP32P4网页图传</title>
    <meta charset="UTF-8">
  </head>
  <body>
    <h1>ESP32P4网页图传：</h1>
    <img src="/video_feed" width="50%">
  </body>
</html>''', 200, {'Content-Type': 'text/html; charset=utf-8'}

@app.route('/video_feed')
def video_feed(request):
    def stream():
        yield b'--frame\r\n'
        while True:
            frame = camera.capture()
            yield b'Content-Type: image/jpeg\r\n\r\n' + frame + \
                b'\r\n--frame\r\n'
            gc.collect()
            #time.sleep_ms(50)

    return stream(), 200, {'Content-Type':
                           'multipart/x-mixed-replace; boundary=frame'}

if __name__ == '__main__':
    app.run(debug=True)
    camera.deinit()
